package cn.niit.letuseatdemo.controller.admin;

import cn.niit.letuseatdemo.common.Constants;
import cn.niit.letuseatdemo.entity.domain.Admin;
import cn.niit.letuseatdemo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 管理员登录
 * @Author Zhang Shiqi
 * @CreateTime 2022/10/22 13:47
 */
@Controller
public class LoginController {
    @Autowired
    private AdminService adminService;

    /**
    * @Description:  显示登录页面
    * @Author: Zhang Shiqi
    * @CreateTime： 2022/10/22 13:51
    * @return: java.lang.String
    **/

    @GetMapping("/admin/login")
    public String loginIndex(){
        return "/admin/login";
    }

    /*
    * @Description: 得到页面信息，验证输入与身份
    * @Author: Zhang Shiqi
    * @CreateTime： 2022/10/31 0:18
     * @param: userName
     * @param: password
     * @param: verifyCode
     * @param: request
     * @return: java.lang.String
    **/
    @PostMapping("/admin/login")
    public String login(String userName, String password, String verifyCode, HttpServletRequest request) {
        System.out.println("userName = " + userName + " password = " + password + "verifyCode = " + verifyCode);

        if (!StringUtils.hasLength(verifyCode)) {
            request.setAttribute("errorMsg", "验证码不能为空！");
            return "/admin/login";
        }
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            request.setAttribute("errorMsg", "账号或者密码不能为空！");
            return "/admin/login";
        }

        //拿去session中保存的验证码
        String kaptchaCode = request.getSession().getAttribute("verifyCode") + "";
        if (!verifyCode.equals(kaptchaCode)) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "/admin/login";
        }

        Admin admin = adminService.getAdminByAdminNamePassword(userName,password);

        //验证账号密码是否正确  数据库
        if (null != admin){

            request.getSession().setAttribute(Constants.ADMIN_SESSION_USER_ID_KEY,admin);//验证账号是否正确
            request.getSession().setAttribute(Constants.ADMIN_SESSION_USER_KEY,admin);
            //验证通过
            //return "index";
            return "redirect:/admin/index";
        }else {
            //账号或密码错误
            request.setAttribute("errorMsg","账号或密码错误！");
            return "/admin/login";
        }


    }


}
